import React, { Component } from 'react'
import { Button, Col, Icon,Modal, message, Popconfirm, Row } from 'antd'
import { TwsBelongTask } from 'tws-antd'
import { connect } from 'react-redux'
import '../less/index.less'
import { withRouter } from 'react-router-dom'
import SingleChoiceQuiz from './common/single-choice-quiz'
import { getTaskInfo } from '../actions/task'
import {
  getAssignment, getAssignmentDuration,
  getReviewQuiz, startAssignment, submitAssignment, submitQuizSuggestion,
} from '../actions/assignment'
import { FormattedMessage } from 'react-intl'
import { convertContent, getLangFromLocalStorage } from '../constant/lang-util'
import QuizSuggestionBox from './common/quiz-suggestion-box'

class AssignmentPageBody extends Component {
  state = {
    assignmentId: -1,
    programId: -1,
    taskId: -1,
    answers: [],
    disable: false
  }

  loadData = () => {
    const {assignmentId, taskId} = this.state
    this.props.getTaskInfo(taskId)
    this.props.getAssignment(assignmentId)
    this.props.getReviewQuiz(assignmentId)
  }

  showStartModal = () => {
    Modal.info({
      title: convertContent('确定开始答题？'),
      okText: convertContent('确定'),
      onOk: () => {
        this.startAssignment()
        this.loadData()
      },
    })
  }

  startAssignment = () => {
    const {taskId, assignmentId} = this.state
    const {user} = this.props
    this.props.startAssignment(user.id, taskId, assignmentId)
  }
  componentDidMount () {
    const {assignmentId,taskId,programId} =  this.props.match.params
    this.setState({assignmentId,taskId,programId}, () => {
      this.props.getAssignmentDuration(taskId, assignmentId, (assignmentDuration) => {
        if (assignmentDuration.id) {
          this.loadData()
        } else {
          this.showStartModal()
        }
      })
    })
  }

  modifyAnswer =(quiz, answer) =>{
    const {answers} = this.state
    const index = answers.findIndex(item => item.quizId === quiz.id)
    if (index !== -1) {
      answers[index].userAnswer = answer
    } else {
      answers.push({quizId: quiz.id, userAnswer: answer})
    }

    this.setState({answers})
  }

  finish = () => {
    const {answers} = this.state
    const {assignment} = this.props
    const {quizzes} = assignment
    return answers.length === quizzes.length
  }

  submitAssignment= ()=> {
    const {answers, assignmentId} = this.state
    if (this.finish()) {
      this.props.submitAssignment(answers, assignmentId)
    } else {
      message.warning(convertContent('还有题目未完成'))
    }
  }

  render () {
    const {assignment, settings,taskInfo} = this.props
    const {assignmentId,taskId,programId} = this.state
    const {assignments,task} = taskInfo
    const {quizzes, reviewQuiz} = assignment
    const {studentHomeUrl} = settings
    const currentAssignment = assignments.find(assignment => assignment.id === assignmentId) || {}
    const lang = getLangFromLocalStorage()

    return <div>
      <div>
        <Row>
          <Col xs={24} sm={4} md={7} lg={8} xl={8}>
            <h2>{currentAssignment[`title_${lang}`] || currentAssignment.title}</h2>
          </Col>
        </Row>
      </div>
      <TwsBelongTask title={<FormattedMessage id={'所属任务卡'}/>}>
        <a href={`${studentHomeUrl}/program/` + programId + '/task/' + taskId}>
          <Icon type='arrow-left'/>
          {task[`title_${lang}`] || task.title}
        </a>
      </TwsBelongTask>
      <div className='margin-t-3'>
        <h3><FormattedMessage id={'作业内容'}/></h3>
        {
          reviewQuiz.id
            ? <span className='submit-time-box'>
              <Icon type='clock-circle'/>
              {reviewQuiz.createTime}
            </span>
            : ''
        }
        <div className='margin-t-2 '>
          <div style={{background: 'white'}}/>
          {
            quizzes.map((quiz, index) => {
              return <div>
                <SingleChoiceQuiz
                  disabled={!!reviewQuiz.id}
                  key={index}
                  index={index}
                  modifyAnswer={this.modifyAnswer}
                  quiz={quiz}/>
                <QuizSuggestionBox
                  settings={settings}
                  quiz={quiz}
                  submit={this.props.submitQuizSuggestion}
                />
              </div>
            })
          }

          {
            reviewQuiz.id
              ? ''
              : <Popconfirm title={<FormattedMessage id='确定提交吗'/>}
                            onConfirm={this.submitAssignment} okText='Yes'
                            cancelText='No'>
                <Button className='margin-t-2 margin-b-3' type='primary'><FormattedMessage id='提交'/></Button>
              </Popconfirm>

          }
        </div>
      </div>


    </div>
  }
}

const mapStateToProps = ({taskInfo,assignment,user,settings}) => ({
  taskInfo,
  assignment,
  user,
  settings
})
const mapDispatchToProps = dispatch => ({
  getTaskInfo: (taskId) => dispatch(getTaskInfo(taskId)),
  getAssignment: (assignmentId) => dispatch(getAssignment(assignmentId)),
  getReviewQuiz: (assignmentId) => dispatch(getReviewQuiz(assignmentId)),
  submitQuizSuggestion: (suggestion,callback) => dispatch(submitQuizSuggestion(suggestion,callback)),
  submitAssignment: (answers, assignmentId) => dispatch(submitAssignment(answers, assignmentId)),
  getAssignmentDuration: (taskId, assignmentId, callback) => dispatch(getAssignmentDuration(taskId, assignmentId, callback)),
  startAssignment: (userId, taskId, assignmentId) => dispatch(startAssignment(userId, taskId, assignmentId)),
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(AssignmentPageBody))
